﻿// Copyright (c) 2008, 3G.cn
// $Author: Moweiqiang $
// $Date: 09-03-23 11:49 $
// $Revision: 6 $
// $NoKeywords: $
namespace Jiubang.Collections {
	using System.Collections;
	using System.Collections.Generic;

	/// <summary>
	/// 可遍历对象的浅层值相等比较器
	/// 设计用于值类型集合的比较
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public class ShallowEnumerableEqualityComparer<T> : IEqualityComparer<T> where T : IEnumerable {
		private static readonly ShallowEnumerableEqualityComparer<T> instance = new ShallowEnumerableEqualityComparer<T>();

		private ShallowEnumerableEqualityComparer () { }
		/// <summary>
		/// 默认实例
		/// </summary>
		public static ShallowEnumerableEqualityComparer<T> Instance {
			get { return instance; }
		}

		#region IEqualityComparer<T> Members

		/// <summary>
		/// 比较两个对象集合数量及各个值是否相同
		/// </summary>
		/// <param name="x"></param>
		/// <param name="y"></param>
		/// <returns></returns>
		public bool Equals (T x, T y) {
			IEnumerator xEnumerator = x.GetEnumerator();
			IEnumerator yEnumerator = y.GetEnumerator();
			while (xEnumerator.MoveNext()) {
				if (!yEnumerator.MoveNext() || !xEnumerator.Current.Equals(yEnumerator.Current)) return false;
			}
			return !yEnumerator.MoveNext();
		}

		/// <summary>
		/// 产生Hashcode
		/// </summary>
		/// <param name="obj"></param>
		/// <returns></returns>
		public int GetHashCode (T obj) {
			long value = 0;
			foreach (object o in obj) {
				value += o.GetHashCode();
			}
			return (int)(value % int.MaxValue);
		}

		#endregion
	}
}